<template>
    <div ref="googleAdStyle">
        <div :id="id" :data-gam-id="id" :data-gam-name="name" style="width: 100%; height: auto;"></div>
    </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted } from 'vue'

const props = defineProps({
    id: {
        type: String,
        required: true
    },
    name: {
        type: String,
        required: true
    },
    parentPage: {
        type: String,
        default: ''
    },
    channel: {
        type: String,
        default: ''
    }
})

const emit = defineEmits(['onNullAd'])
const googleAdStyle = ref(null)
let observer = null
let hasDisplayed = false

const handleIntersection = (entries) => {
    if (entries[0].isIntersecting && !hasDisplayed) {
        hasDisplayed = true
        
        // 上报广告进入视窗事件
        logEvent('GAM_AD_View', {
            AdSlot: props.name,
            Page: props.parentPage
        });

        window.googletag = window.googletag || { cmd: [] }
        googletag.cmd.push(function() {
            // Get the pre-defined ad slot
            const slot = googletag.pubads().getSlots().find(
                s => s.getSlotElementId() === props.id
            )
            
            if (!slot) {
                emit('onNullAd')
                console.log('Slot not found:', {
                    AdSlot: props.name,
                    Page: props.parentPage,
                    Reason: 'Slot not found'
                })
                return
            }

            // 监听广告渲染事件
            let hasReported = false  // 添加标记防止重复上报
            googletag.pubads().addEventListener('slotRenderEnded', function(event) {
                if (event.slot === slot && !hasReported) {
                    hasReported = true
                    if (event.isEmpty) {
                        logEvent('GAM_AD_Show_Fail', {
                            AdSlot: props.name,
                            Page: props.parentPage
                        })
                        emit('onNullAd')
                    } else {
                        logEvent('GAM_AD_Show', {
                            AdSlot: props.name,
                            Page: props.parentPage
                        })
                    }
                }
            })

            // Display the ad
            googletag.display(props.id)
        })

        // Stop observing after first display
        observer.unobserve(googleAdStyle.value)
    }
}

onMounted(() => {
    observer = new IntersectionObserver(handleIntersection)
    observer.observe(googleAdStyle.value)
})

onUnmounted(() => {
    if (observer) {
        observer.disconnect()
        observer = null
    }
})
</script>

<style scoped>
/* Add any custom styles here */
</style> 